package com.foreveross.chameleon.mdm;

import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.foreveross.chameleon.base.PushApplication;
import com.foreveross.chameleon.utils.AppLog;
import com.foreveross.chameleon.utils.httputil.HttpConnection;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by zhouzhineng on 14-9-3.
 * 获取本机已安装程序信息的工具类
 */
public class LocalInstalledAppInfoUtil {

    public final static String TAG = "LocalInstalledAppInfoUtil";
    private Context mContext;
    private String mUrlRecipt;      //回执地址
    private static LocalInstalledAppInfoUtil mInstance;

    public static LocalInstalledAppInfoUtil getInstance() {
        if (mInstance == null) {
            Application app = PushApplication.getApplication();
            mInstance = new LocalInstalledAppInfoUtil(app);
        }
        return mInstance;
    }

    private LocalInstalledAppInfoUtil(Context context) {
        mContext = context;
    }

    public class AppInfo {
        public String packageName;
        public String appName;
        public String versionName;
        public int versionCode;
        public boolean isPrevInstalled;        //是否系统预安装,false为用户自己安装
    }

    /**
     * 设置回执地址
     */
    public void setReciptUrl(String reciptUrl) {
        mUrlRecipt = reciptUrl;
    }

    /**
     * 获取本机安装的app信息列表
     */
    private List<AppInfo> getLocalInstalledAppList() {
        List<AppInfo> items = null;
        PackageManager pkgMgr = mContext.getPackageManager();
        List<PackageInfo> packs = pkgMgr.getInstalledPackages(0);
        int count = packs.size();
        if (count > 0) {
            items = new ArrayList<AppInfo>();
        }
        for (int i = 0; i < count; i++) {

            PackageInfo p = packs.get(i);
            AppInfo item = new AppInfo();
            ApplicationInfo appInfo = p.applicationInfo;
            if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                item.isPrevInstalled = true;
            } else {
                item.isPrevInstalled = false;
            }
            item.appName = p.applicationInfo.loadLabel(pkgMgr).toString();
            item.packageName = p.applicationInfo.packageName;
            item.versionName = p.versionName;
            item.versionCode = p.versionCode;
            items.add(item);

        }
        return items;
    }

    /**
     * 将安装程序信息列表转换成json格式方便提交服务器
     * items 程序信息列表
     */
    private String appInfos2Json(List<AppInfo> items) {
        boolean result = true;
        JSONObject jObj = new JSONObject();
        try {
            jObj.put("desc", "本地安装的应用程序信息列表");
            if (items != null) {
                JSONArray item_arr = new JSONArray();
                for (int i = 0; i < items.size(); i++) {
                    JSONObject item = new JSONObject();
                    item.put("packageName", items.get(i).packageName);
                    item.put("appName", items.get(i).appName);
                    item.put("versionName", items.get(i).versionName);
                    item.put("versionCode", items.get(i).versionCode);
                    item.put("isPreInstalled", items.get(i).isPrevInstalled);
                    item_arr.put(item);
                }
                jObj.put("list", item_arr);
            }
            jObj.put("result", true);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            result = false;

        }
        try {
            jObj.put("result", result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jObj.toString();
    }

    public void execSubmitAppInfo() {
        if (mUrlRecipt == null) {
            AppLog.e(TAG, "回执地址不存在...");
            return;
        }
        AppLog.d(TAG, "发送回执");
        List<AppInfo> appInfos = getLocalInstalledAppList();
        String jsonAppInfos = appInfos2Json(appInfos);
        final List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("cmdResult", jsonAppInfos));
        String resString = HttpConnection.put(mUrlRecipt, params, "application/x-www-form-urlencoded", "application/json");
        AppLog.i(TAG, "the result string == >" + resString);
    }
}
